package com.example.mapperapi.file;

import com.example.mapperapi.annotation.MapperFileString;
import com.example.mapperapi.annotation.MapperFileTo;
import com.example.mapperapi.util.MapperUtil;
import lombok.Data;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

@RestController
@RequestMapping("testx")
public class Test {


    @Autowired
    private FileUtil fileMap;

    @Autowired
    private FileUtil fileUtil;

    @GetMapping("test")
    public String downFile(HttpServletRequest request) throws Exception {
        System.out.println(request.getRequestURL());
        System.out.println(request.getRequestURI());
        System.out.println(request.getRequestURL().toString().replace(request.getRequestURI().toString(), ""));

        B b = new B();
        MapperUtil.mapperObject(new A(), b);
        A a = new A();
        System.out.println("oldUrl:"+a);
        fileUtil.mapperTo(b, a,"http://127.0.0.1:8080/file/");
        System.out.println("newUrl:"+a);
        URL url = new URL(a.url);
        URLConnection urlConnection = url.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
        try (InputStream inputStream = httpURLConnection.getInputStream()) {
            byte[] bytes = MapperUtil.readInputStream(inputStream);
            System.out.println("bytes.length:" + bytes.length);
            String string = Base64.encodeBase64String(bytes);
            System.out.println("Base64.length:" + string.length());
        }
        return "ok";
    }

    @Data
    public static class A {
        private String url = "https://hexo.xuxin.world/iShot_2022-08-15_16.44.39.png";
    }

    @Data
    public static class B {
        @MapperFileString("url")
        @MapperFileTo("url")
        private byte[] pic1;
        @MapperFileString("url")
        private String pic2;
    }
}
